<?php

namespace teach\controllers;

use teach\components\WeChatPay;
use teach\service\Payment;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class PaymentController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    public function actionDirect()
    {
        $spdill_create_ip = $_SERVER['REMOTE_ADDR'];

        $request = Yii::$app->request;

        $name = $request->post('name');//收货人
        $phone = $request->post('phone');//电话
        $address = $request->post('address');//地址

        $mid = $request->post('mid');//商家id
        $pid = $request->post('pid');//产品id
        $uid = $request->post('uid');//用户id
        $sku_id = $request->post('sku_id');//sku表id
        $count = $request->post('count');//购买数量
        $openid = $request->post('openid');//openid
        $value = $request->post('value');//购买的属性值

        $mode = $request->post('mode_id');//1 发起拼单 2 直接购买 3 跟别人拼团

        //判断商户是否存在
        if (!array_key_exists($mid, Yii::$app->params['serviceNum'])) {
            $jsonData = ResponseHelper::buildJsonData(400, '商家支付账号不存在,请联系商家或者开发者');
            return $this->asJson($jsonData);
        }

        //服务商模式下支付
        $appid = Yii::$app->params['serviceNum'][$mid]['appid']; //公众号appid
        $mch_id = Yii::$app->params['serviceNum']['mchId']; //服务商号
        $sub_mch_id = Yii::$app->params['serviceNum'][$mid]['sub_mch_id'];
        $sub_appid = Yii::$app->params['serviceNum'][$mid]['sub_appid']; //小程序appid
        $key = Yii::$app->params['serviceNum']['md5Key']; //支付密匙设置
        $notify_url = Yii::$app->params['serviceNum'][$mid]['notifyUrlAssemble']; //支付回调

        $msg = '';
        $flag = false;
        if (!$openid) {
            $msg = 'openid 用户openid不能为空';
        } elseif (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$pid) {
            $msg = 'pid 产品id不能为空';
        } elseif (!$uid) {
            $msg = 'uid 用户id不能为空';
        } elseif (!$sku_id) {
            $msg = 'sku_id 不能为空';
        } elseif (!$count) {
            $msg = 'count 购买数量不能为空';
        } elseif (!$value) {
            $msg = 'value 购买规格不能为空';
        } elseif (!$name) {
            $msg = 'name 收货人不能为空';
        } elseif (!$phone) {
            $msg = 'phone 电话不能为空';
        } elseif (!$address) {
            $msg = 'address 地址不能为空';
        } elseif (!$appid) {
            $msg = 'appid 不能为空';
        } elseif (!$mch_id) {
            $msg = 'mchid 不能为空';
        } elseif (!$key) {
            $msg = 'key 不能为空';
        } elseif (!$sub_appid) {
            $msg = 'sub_appid不能为空';
        } elseif (!$notify_url) {
            $msg = 'url 不能为空';
        } elseif (!$mode) {
            $msg = '购买模式不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {

            if (!in_array($mode , [1,2,3])) {
                $jsonData = ResponseHelper::buildJsonData(400, '模式错误');
                return $this->asJson($jsonData);
            }

            $group_id = $request->post('group_id');

            if ($mode == 1) {
                $group_id = 'assemble-' . $sku_id . '-'. date('Ymd') . '-' . time();
            }

            if ($mode == 2) {
                $group_id = '';
            }

            if ($mode == 3) {
                if (!$group_id) {
                    $jsonData = ResponseHelper::buildJsonData(400, '团id不能为空');
                    return $this->asJson($jsonData);
                }
            }

            $payments = new Payment();

            $where = $sku_id;
            $andWhere = $pid;
            // 校验订单是否过期 是否下架
            $product = $payments->assembleDetail($where, $andWhere);
            if(!$product) {
                $jsonData = ResponseHelper::buildJsonData(400, '拼团活动已结束,请核实后再下单');
                return $this->asJson($jsonData);
            }

            //判断商品的库存是否还有
            if ($product['stock'] < $count) {
                $jsonData = ResponseHelper::buildJsonData(400, '库存不足');
                return $this->asJson($jsonData);
            }

            //是否超过了限购数量
            if ($product['limited'] < $count) {
                $jsonData = ResponseHelper::buildJsonData(400, '超过限购数量');
                return $this->asJson($jsonData);
            }

            //查找用户信息
            $map = " id = {$uid} AND openid = '{$openid}'";
            $user = $payments->assembleUser($map);

            if (!$user) {
                $jsonData = ResponseHelper::buildJsonData(400, '用户信息有误');
                return $this->asJson($jsonData);
            }

            $out_trade_no = 'No-A' . date('Ymd') . time() . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
            switch ($mode)
            {
                case 1:
                    $product['price'] = $product['assemble_price'];
                    $body = '发起拼团购买';
                    break;
                case 2:
                    $product['price'] = $product['alone_price'];
                    $body = '单独购买';
                    break;
                case 3:
                    $product['price'] = $product['assemble_price'];
                    $body = '拼团购买';
                    break;

            }
//            if ($mode == 3) {
//                //拼团价格
//                $product['price'] = $product['assemble_price'];
//                $body = '拼团购买';
//            } else {
//                //直接购买价格
//                $product['price'] = $product['alone_price'];
//                $body = '单独购买';
//            }
            $total_fee = $product['price'] * $count + $product['freight'];

            $WeiXinPay = new WeChatPay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $notify_url, $spdill_create_ip, $sub_appid, $sub_mch_id);
            //发起微信支付
            $result = $WeiXinPay->pay();
            $status = -1;

            if ($result['code'] == 0) {
                $jsonData = ResponseHelper::buildJsonData(400, '失败', $result['msg']);
                return $this->asJson($jsonData);
            } else {

                //生成预支付成功 对产品进行入库记录
                $order = [
                    'mid' => $mid,
                    'uid' => $uid,
                    'openid' => $openid,
                    'out_trade_no' => $out_trade_no,
                    'total_fee' => $total_fee,
                    'amount' => $total_fee,
                    'logistic_fee' => $product['freight'],
                    'name' => $name,
                    'phone' => $phone,
                    'address' => $address,
                    'create_time' => time(),
                    'status' => $status,
                    'marks' => $request->post('marks'),
                    'mode_id' => $mode,
                    'recharge' => 0,
                    'discount' => 1,
                    'count' => $count,
                    'effective_time' => $product['effective_time'],
                    //
                    'avatar_url' => $user['avatar_url'],
                    'nickname' => $user['nickname'],
                    'group_id' => $group_id,
                    'pid' => $pid,
                    'sku_id' => $sku_id,
                    'value' => $value,
                ];

                $res = $payments->orderInsert($order);

                if ($res) {
                    //获取订单id
                    $orderId = $payments->orderGetId($out_trade_no);
                    $result['oid'] = $orderId['id'];
                    $result['pid'] = $pid;
                    $result['sku_id'] = $sku_id;
                    $result['group_id'] = $group_id;
                    //减去相应的库存
                    $payments->productReduce($sku_id, $count);
                    $jsonData = ResponseHelper::buildJsonData(200, '成功', $result);
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '订单生成失败,请联系管理员');
                }
            }
        }
        return $this->asJson($jsonData);
    }
}